angular.module('starterApp', ['ngMaterial', 'ngMdIcons', 'fbdApp'])
  .factory('testName', function($http, $q) {
    return {
      test: function(url) {

        var deferred = $q.defer();

        $http.get(url).success(function(res) {
          deferred.resolve(res);
          // console.log(res);
        }).error(function(err) {
          deferred.reject(err);
        });
        return deferred.promise;
      }
    };
  })
  .factory('templateList', function($http, $q) {
    return {
      list: function(url) {

        var deferred = $q.defer();

        $http.get(url).success(function(res) {
          // var tpls = [];
          // var temp = {};
          // angular.forEach(res, function(data, index, array) {
          //   temp = data;
          //   var content = JSON.parse(data.content);
          //   temp.content = content;
          //   tpls.push(temp);
          // });
          deferred.resolve(res);
          // console.log(res);
        }).error(function(err) {
          deferred.reject(err);
        });
        return deferred.promise;
      }
    };
  })

.controller('AppCtrl', ['$scope', '$http', '$mdDialog', '$mdToast',
  'fbdService',
  '$filter', 'testName', 'templateList', '$q',
  function($scope, $http, $mdDialog, $mdToast, fbdService,
    $filter,
    testName,
    templateList, $q) {

    $scope.selectIndex = 2;
    $scope.testingData = 'abcd';
    $scope.tplSelected = {};
    $scope.rules = [];
    $scope.mainTabIndex = 1;

    //加载模板列表
    templateList.list('http://localhost:3000/api/templates').then(
      function(data) {
        $scope.allTpls = data;
        console.log(data, 'data');
        $scope.currentTpl = angular.copy($scope.allTpls[$scope.allTpls.length -
          1]);
        console.log($scope.currentTpl, 'currentTpl');
        $scope.tplSelected.name = $scope.currentTpl.name;
        console.log(data);
      },
      function(data) {
        // alert('err');
      });
    //弹出添加模板页面
    $scope.showNewTemplate = function(ev) {
      // alert('aaa');
      $mdDialog.show({
          controller: DialogController,
          templateUrl: 'views/newTemplate.html',
          parent: angular.element(document.body),
          targetEvent: ev,
          clickOutsideToClose: false
        })
        .then(function(answer) {
          $scope.mainTabIndex = 1;
          var id = '';
          $scope.templatename = answer.name;
          var tpldata = {
            "name": answer.name,
            "content": {
              "name": answer.name,
              "expression": answer.mainRule.expression,
              "mode": answer.mainRule.mode,
              "similar": answer.mainRule.similar,
              "limit": answer.mainRule.limit,
              "type": answer.mainRule.type,
              // "validation": "☆",
              "beginText": answer.mainRule.beginText,
              "endText": answer.mainRule.endText,
              "configs": [],
              "subset": []
            }
          };

          fbdService.save('http://localhost:3000/api/templates/add',
            tpldata).then(
            function(data) {
              console.log(data + 'data ')
              id = data._id;
              var newTemplate = {
                "_id": id,
                "name": answer.name,
                "content": tpldata.content,
                "__v": 0
              };
              $scope.currentTpl = angular.copy(newTemplate);
              console.log(newTemplate, 'newTemplate');
              $scope.allTpls.push(newTemplate);
              $scope.tplSelected.name = answer.name;
              // console.log(answer.name, 'tplname');

            },
            function(data) {
              console.log(data);
              alert('err');
            });

          $scope.fileName = answer.fileName;
          $scope.articleList = answer.articleList;

          // $scope.fileName = answer.fileName;
          // console.log(answer);
          // console.log(answer.fileName);
          // alert('确定');
        }, function() {
          // console.log();
          // alert('取消');
        });
    };

    $scope.deleteTemp = function(id) {
      // console.log(id);
      // var tpl = $scope.allTpls[index];
      // console.log($scope.allTpls[index]);
      var confirm = $mdDialog.confirm()
        .title('确认删除')
        .textContent('是否删除模板？一旦删除将不可恢复。')
        // .targetEvent(ev)
        .ok('删除')
        .cancel('取消');

      $mdDialog.show(confirm).then(function() {
        $http.get('http://localhost:3000/api/templates/delete/' + id)
          .success(function(res) {
            if (res) {
              $mdToast.show($mdToast.simple()
                .textContent('删除成功')
                .action('×')
                .position('bottom right')
                .hideDelay(800)
              );
              // console.log('ok');
              // $scope.allTpls.splice(index, 1);
              templateList.list(
                'http://localhost:3000/api/templates').then(
                function(data) {
                  $scope.allTpls = data;
                  $scope.currentTpl = angular.copy($scope.allTpls[
                    $scope.allTpls.length -
                    1]);
                  $scope.tplSelected.name = $scope.currentTpl.name;
                  console.log(data);
                },
                function(data) {
                  // alert('err');
                });

            }
          }).error(function(err) {

          });
      }, function() {

      });
    };

    $scope.testTemplate = function() {
      // console.log($scope.currentTpl);
      // console.log($scope.allTpls);
      if ($scope.fileName) {
        $scope.postTemp = {};
        $scope.postTemp.text = {
          type: 'file',
          content: $scope.fileName
        };
        $scope.postTemp.template = $scope.currentTpl.content;
        $scope.subsetItems = $scope.postTemp.template.subset;
        console.log($scope.subsetItems);
        var promise = fbdService.testTpl(
          'http://localhost:3000/api/templates/detect',
          $scope.postTemp);
        promise.then(function(res) {

          $scope.mainTabIndex = 3;
          $scope.showResult = res;
          console.log($scope.showResult, 'result');

        }, function(err) {
          $scope.showResult = err;
          // console.log(err);
        });
      } else {
        $scope.confirmFileUpload();
        // $scope.testTemplate();
      }

    }

    //新建模板的控制器
    function DialogController($scope, $mdDialog, shareData) {
      $scope.isOkName = false;
      $scope.isUploaded = false;
      $scope.isMainRule = false;
      $scope.step = 0;
      $scope.sure = false;
      $scope.templatename = 'name';
      $scope.ruleObj = {};
      var url = 'http://localhost:3000/api/templates/check/';

      $scope.$watch('fileName', function(v) {
        console.log(v);
      });

      $scope.test = function() {
        $scope.waitResult = true;
        $scope.testObj = {
          type: 'file',
          content: $scope.fileName
        };
        $scope.postData = $filter('testRuleFilter')($scope.ruleObj,
          $scope.testObj);
        var promise = fbdService.testRule(
          'http://localhost:3000/api/rules/detect',
          $scope.postData);
        promise.then(function(res) {
          $scope.waitResult = false;
          // console.log(res.rule);
          $scope.canBeSaved = true;
          // $scope.addData = res.rule;
          // $scope.testRuleResult = {};
          $scope.testResult = res;
          $scope.articleList = res.data;
          // console.log(res);

        }, function(err) {
          $scope.waitResult = false;
          $scope.testResult = err;
        });
      };

      // 监控模板名称可用的时候存进shareData
      $scope.$watch('templatename', function(newval, oldval, scope) {
        if (newval) {
          // shareData.tempName = newval;
          // console.log('shareData.templatename:' + shareData.tempName);
          var promise = testName.test(url + newval);
          promise.then(function(res) {
            $scope.ruleObj.name = newval;
            shareData.tempName = newval;
            $scope.isOkName = res;
            // $scope.step=1;
            console.log(res);
          }, function(err) {
            console.log(err);
          });
        } else {
          $scope.isOkName = false;
        }

      });

      $scope.$on('isUploaded', function(event, data) {
        if (data) {
          $scope.isUploaded = true;
          $scope.step = 2;
          // alert(data);
        }
      });

      $scope.toUploadFile = function() {
        $scope.step = 1;
      }

      $scope.$on('isSaved', function(event, data) {
        if (data) {
          $scope.isMainRule = true;
        }
      });



      $scope.hide = function() {
        // $scope.addData.name = $scope.ruleObj.name;
        // $scope.templatename = $scope.ruleObj.name;
        $scope.testResult.rule.name = $scope.ruleObj.name;
        var res = {
          name: $scope.templatename,
          fileName: $scope.fileName,
          realFileName: $scope.realFileName,
          content: {},

          mainRule: $scope.testResult.rule,
          articleList: $scope.articleList

        };
        console.log(res);
        // var arr = [];
        // arr[0] = $scope;
        $mdDialog.hide(res);
      };
      $scope.cancel = function() {
        // var arr = [];
        // arr[0] = $scope;
        $mdDialog.cancel();
      };
    }
    //展示模板的详细信息
    $scope.showDetailTemplate = function(tpl) {
      // alert('click');

      if ($scope.checkModify()) {
        $scope.showArticles = {};
      } else {
        $scope.currentTpl = angular.copy(tpl);
        $scope.tplSelected.name = tpl.name;
        $scope.showArticles = {};
        // $scope.confirmFileUpload();
      }

      // $scope.currentTpl = tpl;
      // $scope.rules = [];
      // console.log(tpl);
      // $scope.tplSelected.name = tpl.name;
      // if (tpl) {
      //   $scope.mainRule = tpl;
      //   $scope.rules = tpl.subset;
      //   $scope.selectedTpls = tpl.configs;
      // }
      // if (tpl) {
      //   var content = tpl;
      //   var subrules = {};
      //   // console.log(content);
      //   // $scope.mainRule = content.rules[0]
      //   for (var rl in content.rules) {
      //     if (content.rules[rl].hasOwnProperty("mode")) {
      //       console.log(content.rules[rl]);
      //       //被选中模板的主规则
      //       $scope.mainRule = content.rules[rl];
      //       subrules = content.rules[rl]['subset']['rules'];
      //     }
      //     // console.log(rl);
      //   }
      //   for (var subrl in subrules) {
      //     if (subrules[subrl].hasOwnProperty("mode")) {
      //       // alert(subrules[subrl]);
      //       console.log(subrules[subrl]);
      //       //子规则列表
      //       $scope.rules.push(subrules[subrl]);
      //     }
      //   }
      //   console.log($scope.rules);
      // } else {
      //   $scope.mainRule = answer.mainRule;
      //   $scope.rules = [];
      // }


      //提示上传文件
      // $scope.confirmFileUpload();
    };
    //文件上传并按照所选模板的主规则进行切割
    $scope.confirmFileUpload = function(ev) {

      $scope.$on('isUploaded', function(event, data) {
        if (data) {
          $mdDialog.hide();
        }
      });
      //文件上传弹框控制器
      function cfUpload($mdDialog) {
        $scope.closeDialog = function() {
          $mdDialog.cancel();
        }
      }

      $mdDialog.show({
          controller: cfUpload,
          scope: $scope,
          preserveScope: true,
          template: '<md-dialog aria-label="FileUpload dialog">' +
            '<md-dialog-content layout-padding>' +
            '<h1 class="md-display-2" >上传文件</h1>' +
            '<upload-file file-name="fileName" real-file-name="realFileName"></upload-file>' +
            '  </md-dialog-content>' +
            '  <md-dialog-actions>' +
            '    <md-button ng-click="closeDialog()" class="md-primary">' +
            '      取消' +
            '    </md-button>' +
            '  </md-dialog-actions>' +
            '</md-dialog>',
          parent: angular.element(document.body),
          targetEvent: ev,
          clickOutsideToClose: false
        })
        .then(function() {
          // $scope.waitResult = true;
          $scope.testObj = {
            type: 'file',
            content: $scope.fileName
          };
          $scope.postData = $filter('testRuleFilter')($scope.currentTpl
            .content,
            $scope.testObj);
          var promise = fbdService.testRule(
            'http://localhost:3000/api/rules/detect',
            $scope.postData);
          promise.then(function(res) {
            // $scope.waitResult = false;
            // $scope.canBeSaved = true;
            // $scope.addData = res.rule;
            // $scope.testRuleResult = {};
            // $scope.testResult = res;
            $scope.articleList = res.data;

          }, function(err) {
            // $scope.testRuleResult.info = err + '，请重新发送请求';
            // $scope.waitResult = false;
            // $scope.testResult = err;
          });
        }, function() {
          // alert('取消');
        });
    };
    //保存模板到数据库
    $scope.saveTpl = function() {
      var promise = fbdService.save(
        'http://localhost:3000/api/templates/modify', $scope.currentTpl
      );
      promise.then(function(data) {
        if (data) {
          for (var i = 0; i < $scope.allTpls.length; i++) {
            if ($scope.allTpls[i]._id === $scope.currentTpl._id) {
              $scope.allTpls[i] = $scope.currentTpl;
              console.log($scope.allTpls, 'save')
              $mdToast.show($mdToast.simple()
                .textContent('保存成功')
                .action('×')
                .position('bottom right')
                .hideDelay(800)
              );
              return true;
            }

          }
        } else {
          $mdToast.show($mdToast.simple()
            .textContent('保存成功')
            .action('×')
            .position('bottom right')
            .hideDelay(800)
          );
          return false;
        }
      }, function(data) {
        $mdToast.show($mdToast.simple()
          .textContent('保存失败')
          .action('×')
          .position('bottom right')
          .hideDelay(800)
        );
        console.log(data);
        return false;
      })
    };

    //取消保存
    $scope.cancelChange = function() {
      if ($scope.currentTpl.hasOwnProperty('_id')) {
        var ii = '';
        var exist = false;
        for (var i = 0; i < $scope.allTpls.length; i++) {
          if ($scope.allTpls[i]._id === $scope.currentTpl._id) {
            ii = i;
            exist = true;
          }
        }
      }
      if (exist) {
        $scope.currentTpl = $scope.allTpls[ii];
        $mdToast.show($mdToast.simple()
          .textContent('已经放弃保存。')
          .action('×')
          .position('bottom right')
          .hideDelay(800)
        );
      }
      console.log('取消保存');
      return true;
    }

    //检测是否修改了模板
    $scope.checkModify = function(ev) {

      console.log(angular.toJson($scope.currentTpl.content),
        '$scope.currentTpl.content');
      //判断a,b 是否相同
      function isObjectValueEqual(a, b) {
        return angular.toJson(a) == angular.toJson(b);
      }

      var ii = '';
      var exist = false;
      if ($scope.currentTpl.hasOwnProperty('_id')) {


        for (var i = 0; i < $scope.allTpls.length; i++) {
          if ($scope.allTpls[i]._id === $scope.currentTpl._id) {
            ii = i;
            exist = true;
            console.log(ii, 'ii');
          }
        }

        if (exist && isObjectValueEqual($scope.allTpls[ii].content,
            $scope.currentTpl
            .content)) {
          console.log(angular.toJson($scope.allTpls[ii]),
            '$scope.allTpls[ii]');
          return false;
        } else {
          $scope.showConfirm();
          return true;
        }
      } else {

        return false;
      }


    }

    $scope.showConfirm = function(ev) {

      var confirm = $mdDialog.confirm()
        .title('你的修改尚未保存')
        .textContent('是否保存模板' + $scope.currentTpl.name + '的修改？')
        .targetEvent(ev)
        .ok('确定保存')
        .cancel('放弃修改');

      $mdDialog.show(confirm).then(function() {
        $scope.saveTpl();
      }, function() {
        $scope.cancelChange();
      });
    };



    // $scope.items = ['标题', '作者', '内容'];
    // $scope.selectedResult = '';

  }
]);
